<?php

namespace App\Http\Controllers\NewPay;

use App\Http\Controllers\Controller;
use App\Imports\Pay\PayDataImport;
use App\Models\Pay\PayImportData;
use App\Models\Pay\PayImportTemplate;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class PayImportDataController extends Controller
{
    public function payImportDataList(Request $request)
    {
        $params = $request->all();

        if (! $params['month']) {
            $params['month'] = date('d') > 25 ? date('Y-m') : date('Y-m', strtotime('-1 month'));
        } else {
            $params['month'] = date('Y-m', strtotime($params['month']));
        }

        $params['month'] .= '-01';

        $data = $this->getPayImportDataList($params)->get()->groupBy('table_name')->toArray();

        $data = $this->transData($data);

        $tables = [];
        $tableNames = PayImportTemplate::query()->groupBy('table_name')->pluck('table_name', 'table_name')->toArray();
        foreach ($tableNames as $tableName) {
            $tables[] = [
                'label' => $tableName,
                'value' => $tableName,
            ];
        }
        $defaultActiveKey = $data ? key($data) : '';

        return response()->formatJson([
            'result' => $data, 'defaultActiveKey' => $defaultActiveKey, 'tables' => $tables, 'month' => $params['month'],
        ]);
    }

    public function getPayImportDataList($params): Builder
    {
        $query = PayImportData::query()
            ->where('month', $params['month']);

        if (isset($params['name'])) {
            $query->where('name', 'like', '%'.$params['name'].'%');
        }

        return $query;
    }

    public function transData($data): array
    {
        $result = [];
        foreach ($data as $tableName => $tableData) {
            $fields = PayImportTemplate::query()->where('table_name',
                $tableName)->orderBy('sort')->pluck('column_name')->toArray();
            $column = [];
            foreach ($fields as $k => $v) {
                $column[] = ['title' => $v, 'key' => $v, 'minWidth' => 100];
            }
            $columnData = array_column($tableData, 'data');

            $ignoreKey = ['姓名', '出勤天数', '线路', '备注', '类别', '身份证号', '人员类型'];
            foreach ($columnData as $kk => $vv) {
                $data = json_decode($vv, true);
                foreach ($data as $kkk => $vvv) {
                    if (! in_array($kkk, $ignoreKey, true)) {
                        $data[$kkk] = $vvv ? number_format($vvv, 2, '.', '') : 0;
                    }
                }
                $columnData[$kk] = $data;
            }

            $result[$tableName] = [
                'data' => $columnData,
                'columns' => $column,
                'label' => $tableName,
                'value' => $tableName,
            ];
        }

        return $result;
    }

    /**
     *  导入行政人员数据
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function importPayData(Request $request)
    {
        $params = $request->all();
        $urlParse = parse_url($params['url']);
        $month = $params['form']['month'].'-01';
        $tableName = $params['form']['table_name'];

        // 读取文件内容
        $import = new PayDataImport();
        Excel::import($import, public_path().$urlParse['path']);
        $fullData = $import->sheetData;

        $allData = [];
        $fields = PayImportTemplate::query()->where('table_name',
            $tableName)->orderBy('sort')->pluck('column_name')->toArray();
        foreach ($fullData as $sheet => $sheetData) {
            // 删除表头
            $titles = array_shift($sheetData);
            foreach ($sheetData as $k => $row) {
                $item = [];
                foreach ($fields as $field) {
                    foreach ($titles as $key => $title) {
                        if ($field === $title) {
                            $item[$field] = $row[$key] ?? 0;
                        }
                    }
                }
                if (isset($item['姓名'])) {
                    $item['姓名'] = str_replace(' ', '', $item['姓名']);
                }
                if (isset($item['备注'])) {
                    $item['备注'] = $item['备注'] ?? '';
                }
                $IDCard = null;
                if (isset($item['身份证号']) && $item['身份证号'] !== '') {
                    $IDCard = (string) $item['身份证号'];
                }
                $allData[] = [
                    'table_name' => $tableName,
                    'name'       => $item['姓名'],
                    'month'      => $month,
                    'IDCard'     => $IDCard,
                    'data'       => json_encode($item),
                ];
            }
        }

        foreach ($allData as $k => $item) {
            PayImportData::query()->updateOrCreate(
                [
                    'table_name' => $item['table_name'],
                    'month'      => $item['month'],
                    'name'       => $item['name'],
                ],
                $item
            );
        }

        return response()->formatJson(['result' => true, 'count' => count($allData)], '导入成功');
    }
}
